//
//  cityView.m
//  AddressPickerView
//
//  Created by mac on 2017/5/14.
//  Copyright © 2017年 zeasn. All rights reserved.
//

#import "CityView.h"


@implementation CityView
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
        //从plist中获取数组和字典
        NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"area" ofType:@"xml"];
        NSString *str = [NSString stringWithContentsOfFile:plistPath encoding:NSUTF8StringEncoding error:nil];
        NSDictionary *listDic = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
        NSDictionary *areaDic = [listDic objectForKey:@"list"];
        provinceArray = [areaDic objectForKey:@"province"];
        
        //所有省对应的城市和区
        cityDic = [[NSMutableDictionary alloc]init];
        
        for (int i = 0; i<provinceArray.count; i++) {
            NSDictionary *proviceDic = [provinceArray objectAtIndex:i];
            provinceStr = [proviceDic objectForKey:@"name"];//省
        }
        
        
        
        //透明黑
        baseView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,KScreenWidth,KScreenHeight)];
        baseView.backgroundColor = [UIColor colorWithWhite:0 alpha:.5];
        
        UITapGestureRecognizer *baseViewTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(baseViewTapAction:)];
        [baseView addGestureRecognizer:baseViewTap];
        [self addSubview:baseView];
        
        
        _pickerView = [[UIView alloc] initWithFrame:CGRectMake(60*SCREEN_WIDTH_RATIO47, (KScreenHeight-KScreenHeight/2)/2, KScreenWidth-120*SCREEN_WIDTH_RATIO47, KScreenHeight/2)];
        _pickerView.backgroundColor = [UIColor whiteColor];
        _pickerView.layer.cornerRadius = 9.0;
        [baseView addSubview:_pickerView];
        
        
        
        
        
        UILabel *promptLab = [[UILabel alloc] init];
        
        promptLab.text = @"选择城市";
        promptLab.font = FontP(16);
        promptLab.textAlignment = NSTextAlignmentCenter;
        promptLab.backgroundColor = Colorbackground;
        promptLab.layer.masksToBounds = YES;
        promptLab.frame = CGRectMake(0, 0, _pickerView.frame.size.width, 40*SCREEN_WIDTH_RATIO47);
        

        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:promptLab.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(9, 9)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = promptLab.bounds;
        maskLayer.path = maskPath.CGPath;
        promptLab.layer.mask = maskLayer;
        [_pickerView addSubview:promptLab];

        
        
        
        CGFloat btnWhidth=_pickerView.width/2;
        //取消
        UIButton *cancleBt = [UIButton buttonWithType:UIButtonTypeCustom];
        cancleBt.frame = CGRectMake(0,_pickerView.height-40*SCREEN_WIDTH_RATIO47, btnWhidth, 40*SCREEN_WIDTH_RATIO47);
        [cancleBt setTitle:@"取消" forState:UIControlStateNormal];
        cancleBt.backgroundColor = Colorbackground;
        [cancleBt addTarget:self action:@selector(cancleAction:) forControlEvents:UIControlEventTouchUpInside];
        [cancleBt setTitleColor:[self colorWithHexString:@"#141414"] forState:UIControlStateNormal];
        
        
        UIBezierPath *maskPathcancleBt = [UIBezierPath bezierPathWithRoundedRect:cancleBt.bounds byRoundingCorners:UIRectCornerBottomLeft  cornerRadii:CGSizeMake(9, 0)];
        CAShapeLayer *maskLayercancleBt = [[CAShapeLayer alloc] init];
        maskLayercancleBt.frame = cancleBt.bounds;
        maskLayercancleBt.path = maskPathcancleBt.CGPath;
        cancleBt.layer.mask = maskLayercancleBt;
        [_pickerView addSubview:cancleBt];
        
        
        //确定
        UIButton *confirmBtRL = [UIButton buttonWithType:UIButtonTypeCustom];
        confirmBtRL.frame = CGRectMake(cancleBt.right, _pickerView.height-40*SCREEN_WIDTH_RATIO47, btnWhidth, 40*SCREEN_WIDTH_RATIO47);
        [confirmBtRL setTitle:@"确定" forState:UIControlStateNormal];
        confirmBtRL.backgroundColor = Colorbackground;
        [confirmBtRL addTarget:self action:@selector(confirmAction:cityStr:) forControlEvents:UIControlEventTouchUpInside];
        [confirmBtRL setTitleColor:[self colorWithHexString:@"#141414"] forState:UIControlStateNormal];
        
        
        
        UIBezierPath *maskPathconfirmBtRL= [UIBezierPath bezierPathWithRoundedRect:confirmBtRL.bounds byRoundingCorners: UIRectCornerBottomRight cornerRadii:CGSizeMake(9, 9)];
        CAShapeLayer *maskLayerconfirmBtRL = [[CAShapeLayer alloc] init];
        maskLayerconfirmBtRL.frame = confirmBtRL.bounds;
        maskLayerconfirmBtRL.path = maskPathconfirmBtRL.CGPath;
        confirmBtRL.layer.mask = maskLayerconfirmBtRL;
        [_pickerView addSubview:confirmBtRL];
        
        
        //picker
        picker = [[UIPickerView alloc] initWithFrame: CGRectMake(0, 20, KScreenWidth-120*SCREEN_WIDTH_RATIO47, KScreenHeight/2-50*SCREEN_WIDTH_RATIO47)];
        picker.dataSource = self;
        picker.delegate = self;
        picker.showsSelectionIndicator = YES;
        [picker selectRow: 0 inComponent:0 animated: YES];
        [picker reloadAllComponents];
        
        
        
        [_pickerView addSubview:picker];
        
        
    }
    return self;
}

#pragma mark- Picker Data Source Methods

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return provinceArray.count;
    
    
}
#pragma mark - 该方法返回的NSString将作为UIPickerView中指定列和列表项的标题文本
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    
    if (0 == component) {
        
        provinceStr =provinceArray[row][@"name"];
    }
    return provinceStr;
    
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.frame = CGRectMake(0, 0, ((KScreenWidth-60)-40)/3*SCREEN_WIDTH_RATIO47, 30*SCREEN_WIDTH_RATIO47);
        pickerLabel.numberOfLines = 0;
        pickerLabel.textAlignment=NSTextAlignmentCenter;
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:FontP(16)];
    }
    // Fill the label text here
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}


- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component;
{
    
    return (KScreenWidth-60)/3;
}
#pragma mark - 当用户选中UIPickerViewDataSource中指定列和列表项时激发该方法
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
    
    
    [pickerView reloadAllComponents];
}


#pragma mark -UIButton action
- (void)baseViewTapAction:(UITapGestureRecognizer *)tap {
    [baseView removeFromSuperview];
    baseView = nil;
    if ([self.delegate respondsToSelector:@selector(baseViewTapAction:)]) {
        [self.delegate baseViewTapAction:tap];
    }
    
  
}

- (void)cancleAction:(UIButton *)sender
{
    [baseView removeFromSuperview];
    if ([self.delegate respondsToSelector:@selector(cancleAction:)]) {
        [self.delegate cancleAction:sender];
    }
}

- (void)confirmAction:(UIButton *)sender cityStr:(NSString *)cityStr
{
    if ([self.delegate respondsToSelector:@selector(confirmAction:cityStr:)]) {
        [self.delegate confirmAction:sender cityStr:provinceStr];
    }
    [baseView removeFromSuperview];
}

#pragma mark-颜色
- (UIColor *) colorWithHexString: (NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
        if ([cString hasPrefix:@"#"])
            cString = [cString substringFromIndex:1];
            if ([cString length] != 6)
                return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
@end
